<template>
  <section class="app-inner">
    <el-dialog :visible.sync="dialogVisible" v-if="dialogVisible"
      :before-close="handleClose" top="5vh" width="80%"
      :title="title" center modal>
      <el-scrollbar>
      <div class="leftTree">
        <el-input placeholder="输入关键字进行过滤" v-model="filterText" class="searchCss"></el-input>
        <el-tree class="filter-tree" :data="treeData" :props="defaultProps" @node-click="clickNodeFn"
          default-expand-all node-key="id" :highlight-current="true" :current-node-key="classId"
          :default-checked-keys='[classId]' :filter-node-method="filterNode" ref="tree" :indent="6">
        </el-tree>
      </div>
      <div class="rightTable">
        <div class="top">
          <el-form :inline="true" :model="queryParams"
           size="small" label-width="84px" class="searchWrapper">
            <el-form-item label="学生姓名" :label-width="labelWidth" class="line">
                <el-input clearable class="inputCss"
                  v-model="queryParams.studentName" placeholder="请输入姓名"></el-input>
            </el-form-item>
            <el-form-item label="性别" :label-width="40+'px'" class="line">
                <el-select v-model="queryParams.gender"  clearable placeholder="请选择性别" class="inputCss" auto-complete="off">
                    <el-option label="未知性别" value="0"></el-option>
                    <el-option label="男" value="1"></el-option>
                    <el-option label="女" value="2"></el-option>
                    <el-option label="未说明的性别" value="9"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="学号" :label-width="40+'px'" class="line">
                <el-input clearable placeholder="请输入学号"
                class="inputCss" v-model="queryParams.eduNum"></el-input>
            </el-form-item>
            <el-form-item class="btnCss card-flex">
                <el-button type="primary" @click="search">查询</el-button>
                <el-button type="primary" @click="restForm">重置</el-button>
                <div class="switch-btn cursor iconfont" :class="[isShow ? 'icon-biyan': 'icon-yanjing']" @click="handleClickIsShow"></div>
            </el-form-item>
          </el-form>
        </div>
        <div class="add">
          <el-button type="text" @click="addStudent" :disabled="!flag">+ 添加</el-button>
          <el-button type="text" icon="el-icon-delete" @click="delStudent" :disabled="!flag">删除</el-button>
           <!-- <el-button type="text" icon="el-icon-user">换组织</el-button> -->
          <el-upload
            style="display: inline; margin-left: 10px"
            :show-file-list="false"
            action="no"
            class="itemBtn"
            :before-upload="beforeUpload"
            :http-request="importExcel"
            :disabled="!flag"
          >
            <el-button type="text" icon="el-icon-paperclip" :disabled="!flag">导入</el-button>
          </el-upload>
          <el-button type="text" icon="el-icon-paperclip" @click="exportStudent">导出</el-button>
           <!-- <el-button type="text" icon="el-icon-video-play" class="btnItem">启用账号</el-button> -->
           <!-- <el-button type="text" icon="el-icon-remove-outline" class="btnItem">禁用账号</el-button> -->
           <!-- <el-button type="text" icon="el-icon-lock" class="btnItem">重置密码</el-button> -->
        </div>
        <div class="tableBottom">
            <el-table
            :row-key="bindRowKey"
            ref="multipleTable" :data="studentTableData"
            tooltip-effect="dark" style="width: 100%"
            @selection-change="handleSelectionChange">
              <el-table-column type="selection" :reserve-selection="true" width="100"></el-table-column>
              <el-table-column prop="eduNo" label="学号" width="90"></el-table-column>
              <el-table-column prop="studentName" label="姓名" show-overflow-tooltip></el-table-column>
              <el-table-column prop="gender" label="性别" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{scope.row.gender === 0 ? '未知性别' : scope.row.gender === 1 ? '男'
                    :  scope.row.gender === 2 ? '女' : '未说明的性别'}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="birthday" label="出生日期" show-overflow-tooltip></el-table-column>
              <el-table-column prop="account" label="账号" show-overflow-tooltip></el-table-column>
              <el-table-column prop="imageUrl" label="照片" show-overflow-tooltip>
                <template slot-scope="scope">
                  <!-- <img :src="scope.row.imageUrl" class="imgCss" v-show="scope.row.imageUrl!==null" /> -->
                  <el-image
                    :style="{ 'max-width': '50px', 'max-height': '50px' }"
                    :src="`/gateway/api/basic/minio/getFileSource?fileName=${scope.row.imageUrl}`"
                    :preview-src-list="[
                      `/gateway/api/basic/minio/getFileSource?fileName=${scope.row.imageUrl}`,
                    ]"
                  >
                    <div slot="error" class="image-slot"></div>
                  </el-image>
                </template>
              </el-table-column>
              <el-table-column prop="contact" label="联系方式" show-overflow-tooltip>
                <template #default='{row}'>
                  {{ !isShow ? $options.filters.cellularPhone(row.contact) : row.contact || '--' }}
                </template>
              </el-table-column>
              <el-table-column prop="status" label="账号状态" show-overflow-tooltip>
                <template slot-scope="scope">
                  <span>{{!scope.row.account || scope.row.status === null ? '' :
                    scope.row.status === 0 ? '禁用' : '启用'}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="nationRes" label="民族" show-overflow-tooltip></el-table-column>
            </el-table>
            <el-pagination
                class="paginationCss"
                v-if="studentTableData.length > 0"
                layout="total, prev, pager, next"
                @current-change="changePage"
                :current-page="queryParams.pageNum"
                :page-size="queryParams.pageSize"
                :total="totalCount"
            ></el-pagination>
        </div>
      </div>
      </el-scrollbar>
    </el-dialog>
    <add-student-table ref="addStudentTable" @selectStudent="selectStudent"></add-student-table>
  </section>
</template>

<script>
import { inClassStudent, seeOrganization, studentImport, exportStudent, delStudent } from '../js/class.js'
import addStudentTable from './addStudentTable.vue'
import { Message } from 'element-ui'
export default {
  name: 'studentManage',
  components: { addStudentTable },
  data () {
    return {
      dialogVisible: false,
      title: '',
      filterText: '',
      labelWidth: '80px',
      totalCount: 0,
      rowData: {},
      flag: 1, // 默认是当前班级信息
      treeData: [
        // {
        //   id: 1,
        //   label: '黄卢一小',
        //   children: [
        //     {
        //       id: 4,
        //       label: '一年级',
        //       children: [
        //         {
        //           id: 3,
        //           label: '1班'
        //         },
        //         {
        //           id: 4,
        //           label: '2班'
        //         }
        //       ]
        //     },
        //     {
        //       id: 2,
        //       label: '二年级',
        //       children: [
        //         {
        //           id: 5,
        //           label: '1班'
        //         },
        //         {
        //           id: 6,
        //           label: '2班'
        //         }
        //       ]
        //     }
        //   ]
        // }
      ],
      bindRowKey (row) {
        return row.studentNo
      },
      queryParams: {
        eduNum: '',
        gender: '',
        studentName: '',
        classNo: '',
        pageNum: 1,
        pageSize: 10
      },
      nationList: [],
      tableData: [],
      defaultProps: [],
      studentTableData: [],
      multipleSelection: [],
      classId: '',
      isShow: false
    }
  },
  computed: {},
  watch: {
    filterText (val) {
      this.$refs.tree.filter(val)
    },
    studentTableData (val) {
      val.forEach(item => {
        this.multipleSelection.forEach(self => {
          if (item.studentNo === self.studentNo) {
            this.$refs.multipleTable.toggleRowSelection(item, true)
          }
        })
      })
    }
  },
  methods: {
    handleClickIsShow () {
      this.isShow = !this.isShow
    },
    add (row) {
      this.classId = row.classNo
      this.rowData = row
      this.flag = row.flag
      let queryParams = {
        ...this.queryParams,
        classNo: row.classNo
      }
      this.queryParams.classNo = row.classNo
      this.getClassStudent(queryParams)
      this.getOrganization(row.status)
      this.dialogVisible = true
    },

    // 导入前的验证
    beforeUpload (file) {
      const extension = file.name.split('.')[1] === 'xls'
      const extension2 = file.name.split('.')[1] === 'xlsx'
      const isLt2M = file.size / 1024 / 1024 < 5
      if (!extension && !extension2) {
        this.$message.warning('上传模板只能是 xls、xlsx格式!')
        return false
      } else if (!isLt2M) {
        this.$message.warning('上传模板大小不能超过 5MB!')
        return false
      } else {
        return true
      }
    },

    // EXCEL导入
    importExcel (file, fileList) {
      let headFile = file.file
      let formData = new FormData()
      formData.append('file', headFile)
      studentImport({ formData, classNo: this.queryParams.classNo }).then((res) => {
        if (res.code === 0) {
          this.$message.success('导入成功')
          this.getClassStudent(this.queryParams)
        }
      })
    },

    // 导出
    async exportStudent () {
      let res = await exportStudent(this.queryParams.classNo)
      if (res.code === 0) {
        this.$message.success('导出成功！')
      } else {
        this.$message.error(res.msg)
      }
    },

    // 获取左边树形结构
    async getOrganization (status) {
      let res = await seeOrganization({ status })
      if (res.code === 0) {
        let tempArr = []
        let oneObj = {}
        oneObj.id = 1
        oneObj.label = res.data.schoolName
        oneObj.children = []
        res.data.classGradeList.forEach(item => {
          let twoObj = {}
          twoObj.id = item.gradeNo
          twoObj.label = item.gradeName
          twoObj.children = []
          item.classesRespList.forEach(cItem => {
            twoObj.children.push({ id: cItem.classNo, label: cItem.name })
          })
          oneObj.children.push(twoObj)
        })
        tempArr.push(oneObj)
        this.treeData = tempArr
      }
    },

    // 选中某个树节点后 重新获取列表数据
    clickNodeFn (val) {
      if (val.children && val.children.length > 0) {
        return
      } else {
        this.queryParams.classNo = val.id
        this.rowData.classNo = val.id
      }
      this.queryParams.pageNum = 1
      this.getClassStudent(this.queryParams)
      this.$refs.multipleTable.clearSelection()
    },

    // 获取班级里的学生列表
    async getClassStudent (data) {
      let res = await inClassStudent(data)
      if (res.code === 0) {
        this.studentTableData = res.data.records
        this.totalCount = res.data.total
      }
      let nation = '民族'
      this.nationList = this.$dictionary[nation]
      this.studentTableData.forEach(item => {
        this.nationList.forEach(naItem => {
          if (item.nation === naItem.code) {
            item.nationRes = naItem.name
          }
        })
      })
    },

    // 关闭弹窗
    handleClose () {
      this.multipleSelection = []
      this.$refs.multipleTable.clearSelection()
      Object.assign(this.$data, this.$options.data())
      this.dialogVisible = false
    },

    // 筛选树节点
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },

    // 搜索
    search () {
      // let query = {
      //   ...this.queryParams
      // }
      this.queryParams.pageNum = 1
      this.getClassStudent(this.queryParams)
      this.$refs.multipleTable.clearSelection()
    },

    restForm () {
      this.queryParams.studentName = ''
      this.queryParams.gender = ''
      this.queryParams.eduNum = ''
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.getClassStudent(this.queryParams)
    },

    // 添加学生
    addStudent () {
      let row = this.rowData
      const type = 'studentManage'
      this.$refs.addStudentTable.add({ row, type })
    },

    // 删除学生
    async delStudent () {
      this.setArr()
      let studentNos = []
      this.multipleSelection.forEach(item => {
        studentNos.push(item.studentNo)
      })
      if (studentNos.length === 0) {
        this.$message.error('请选择要删除的学生！')
      } else {
        let query = {
          classNo: this.queryParams.classNo,
          studentNos
        }
        this.$confirm('确定删除吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          try {
            let res = await delStudent(query)
            if (res.code === 0) {
              this.$message.success('删除成功')
              this.getClassStudent(this.queryParams)
              this.$refs.multipleTable.clearSelection()
            } else {
              this.$message.error(res.msg)
            }
          } catch (e) {}
        }).catch(() => {})
      }
    },

    // 选中的数据做去重
    setArr () {
      let teacherArr = []
      let obj = {}
      this.multipleSelection.forEach((item) => {
        if (obj[item.studentNo]) {
          return 0
        } else {
          obj[item.studentNo] = true
          teacherArr.push(item)
        }
        // obj[item.code] ? '' : obj[item.code] = true && teacherArr.push(item)
      })
      this.multipleSelection = teacherArr
    },

    async selectStudent () {
      Message({
        type: 'success',
        message: '添加学生成功'
      })
      this.queryParams.pageNum = 1
      await this.getClassStudent(this.queryParams)
      this.$refs.multipleTable.clearSelection()
    },
    // 学生列表选择框
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    // 更改页数
    changePage (val) {
      this.queryParams.pageNum = val
      this.getClassStudent(this.queryParams)
    }
  },
  mounted () {}
}
</script>
<style scoped lang="scss">
.app-inner {
  overflow: hidden;
  /deep/ .foot {
    text-align: center;
    > * {
      margin: 20px 80px;
    }
  }
//   .leftTree {
//     width: 12%;
//     border-right: 1px solid #ccc;
//   }
  .leftTree {
        display: inline-block;
        border-right: 1px solid #ccc;
        width: 13%;
    }
    .rightTable {
        display: inline-block;
        float: right;
        width: 87%;
        .top {
            height: 30px;
            .btnCss {
                margin-right: 40px;
            }
        }
        .add {
            margin-left: 10px;
            .btnItem {
                width: 75px;
            }
        }
    }
}
.searchCss {
    height:30px;
    margin-bottom: 10px;
}
/deep/ .el-input__inner {
    font-size: 12px;
    width: 97%;
    height:30px;
}
/deep/.el-dialog {
  min-height: auto;
}
.paginationCss {
  text-align: right;
}
/deep/ .el-dialog__body {
  overflow: hidden;
}
.imgCss {
  width: 40px;
  height: 40px;
}
.inputCss {
  width: 140px;
}

// .abow_dialog {
//   display: flex;
//   justify-content: center;
//   align-items: Center;
//   overflow: hidden;
//   .el-dialog {
//     margin: 0 auto !important;
//     height: 90%;
//     overflow: hidden;
//     .el-dialog__body {
//       position: absolute;
//       left: 0;
//       top: 54px;
//       bottom: 0;
//       right: 0;
//       padding: 0;
//       z-index: 1;
//       overflow: hidden;
//       overflow-y: auto;
//     }
//   }
// }

</style>
